<template>
  <div class="concat-page">
    <div class="concat-item flex">
      <div class="concat-ietm-label">连接模式：</div>
      <div class="concat-radios flex">
        <div class="cursor flex" @click="changeConcat('Rule')">
          <img v-if="concatMode == 'Rule'" src="~@/assets/gou.png" alt="" />
          <img v-else src="~@/assets/circle.png" alt="" />
          <div
            style="margin-left: 12px; margin-right: 5px"
            :class="concatMode == 'Rule' ? 'chooseColor' : 'radio-color'"
          >
            自动分流
          </div>
          <div class="concat-tip-div">
            <img class="explain explain1" src="~@/assets/explain.png" alt="" />
            <div class="concat-tip concat-tip1">访问国际自动代理，国内不代理</div>
          </div>
        </div>
        <div class="cursor flex" @click="changeConcat('Global')">
          <img v-if="concatMode == 'Global'" src="~@/assets/gou.png" alt="" />
          <img v-else src="~@/assets/circle.png" alt="" />
          <div
            style="margin-left: 12px; margin-right: 5px"
            :class="concatMode == 'Global' ? 'chooseColor' : 'radio-color'"
          >
            全局模式
          </div>
          <div class="concat-tip-div">
          <img class="explain explain2" src="~@/assets/explain.png" alt="" />
          <div class="concat-tip concat-tip2">国际国内都强制代理</div>
          </div>
        </div>
      </div>
    </div>
    <div class="concat-item flex" style="margin: 45px 0 60px 0">
      <div class="concat-ietm-label">节点选择：</div>
      <div class="concat-div flex">
        <input
          :placeholder="chooseNode == null ? '正在加载节点...' : chooseNode"
          class="concat-input cursor"
          v-model="chooseNode"
          v-bind:readonly="true"
          @focus="showNodeDialog"
        />
        <img
          class="cursor"
          style="width: 46px; height: 46px; margin-left: 10px"
          src="~@/assets/lightning.png"
          title="刷新节点"
          @click="getNodeList(true)"
        />
        <img class="down-icon cursor" src="~@/assets/down.png" alt="" />
      </div>
    </div>
    <div class="click-btns">
      <div :class="isStart ? 'start-end-div' : ''">
        <img
          class="startorstop cursor"
          @click="changeStatus(true)"
          v-if="!isStart"
          src="~@/assets/start.png"
          alt=""
        />
        <img
          class="startorstop cursor"
          @click="changeStatus(false)"
          v-else
          src="~@/assets/stop.png"
          alt=""
        />
      </div>
      <div
        class="flex chooseColor"
        style="width: 100%; margin-top: 10px; position: relative"
      >
        <img
          src="~@/assets/bottom-shadow.png"
          style="
            width: 207px;
            height: 27px;
            position: absolute;
            top: -10px;
            left: 0;
          "
          alt=""
        />
        <span :style="isStart ? '' : 'color: #FE2627'">{{
          isStart ? "已连接" : "未连接"
        }}</span>
      </div>
    </div>
    <el-dialog
      title="节点选择"
      center
      width="720px"
      :visible.sync="nodeDialog"
      :before-close="handleClose"
      append-to-body
    >
      <!-- :close-on-click-modal="false" -->
      <el-form v-loading="loading">
        <div class="node-list flex">
          <div
            class="node-item cursor flex"
            @click="chooseedNode(item)"
            v-for="(item, key) in nodeList"
            :key="key"
          >
            <div
              :class="
                item === dialogChooseNode
                  ? 'node-left-line choose-tip'
                  : 'node-left-line'
              "
            ></div>
            <div
              :class="
                item === dialogChooseNode
                  ? 'node-item-box choose-node-item'
                  : 'node-item-box'
              "
            >
              <div class="node-item-title">{{ item.title }}</div>
              <div class="flex" style="justify-content: flex-start">
                <div
                  class="node-item-tip flex"
                  style="border: 1px solid #07be2a; color: #07be2a"
                  v-if="item.delay > 1 && item.delay <= 100"
                >
                  极速
                </div>
                <div
                  class="node-item-tip flex"
                  style="border: 1px solid #efc930; color: #efc930"
                  v-if="item.delay > 100 && item.delay <= 500"
                >
                  延迟
                </div>
                <div
                  class="node-item-tip flex"
                  style="border: 1px solid #fe2627; color: #fe2627"
                  v-if="item.delay == 10000"
                >
                  超时
                </div>
                <div style="color: #ffffff">
                  {{ item.delay == 10000 ? "timeout" : item.delay + "ms" }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-form>
      <div class="dialog-btns cursor flex">
        <div class="dialog-cancel flex" @click="dialogCancle">取消</div>
        <div class="dialog-confirm chooseColor flex" @click="dialogConfirm">
          确定
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
const { exec } = require('child_process');
const path  = require('path');
const { remote  } = require('electron')
const app = remote.app
import {setModeCoreAPI,getAllNodeCoreAPI,changeNodeCoreAPI} from '../../utils/api'
import {getProxyConfig,writeConfigToPath} from '../../utils/fileUtils'
export default {
  name: "concat-page",
  data() {
    return {
      loading:false,
      isStart:false,
      concatMode: 'Rule',
      chooseNode: "",
      dialogChooseNode:"",
      nodeDialog: false,
      nodeList:[],
      isRefresh: false,
    };
  },
  methods: {
    changeConcat(mode) {
      if(this.isStart){
        this.$message.error('请先断开连接')
        return
      }
      if(this.$localStore.get("isExpire") && this.nodeList.length == 0){
        this.$message.info('当前无可用节点，请购买会员套餐')
        return
      }
      this.concatMode = mode;
      this.setConcatMode(mode)
    },
    changeStatus(status){
      if(this.$localStore.get("isExpire") && this.nodeList.length == 0){
        this.$message.info('当前无可用节点，请购买会员套餐')
        return
      }
      if(!this.$localStore.get("isExpire") && this.nodeList.length == 0){
        this.$message.info('系统异常，请重新登录')
      }
      if(this.chooseNode == '' || this.chooseNode == null){
        this.$message.error('请选择节点')
        return
      }
      if(status == false){this.$electron.ipcRenderer.send("dis-connect")}
      this.$localStore.set("currentNode",this.chooseNode)
      this.settingNode(this.chooseNode)
      this.isStart = status
      this.$store.commit('CHANGE_ISSART',status)
      this.$localStore.set("isStart",this.isStart)
      this.setProxyHomeConfig();
    },
    showNodeDialog() {
      if(this.$localStore.get("isExpire") && this.nodeList.length == 0){
        this.$message.info('当前无可用节点，请购买会员套餐')
        return
      }
      if(this.chooseNode == null){
        this.$message.info('正在更新节点信息，请稍后')
        return
      }
      this.getNodeList(true)
      this.nodeDialog = true;
      this.dialogChooseNode = this.chooseNode
    },
    handleClose() {},
    //选择节点
    chooseedNode(node){
      this.dialogChooseNode = node
    },
    // 确定
    dialogConfirm(){
      if(this.dialogChooseNode == ''){
        this.$message.error('请选择节点')
        return
      }
      this.chooseNode = this.dialogChooseNode.title || this.chooseNode
      this.dialogCancle()
    },
    //取消
    dialogCancle(){
      this.dialogChooseNode = ''
      this.nodeDialog = false
    },

    //设置/切换连接模式
    setConcatMode(model){
      setModeCoreAPI({mode:model}).then(res=>{
        if(res){}else{}
      })
    },
    // 获取最小延迟节点
    handleMinDelayNode(isRefresh){
      const data = isRefresh == true ? this.nodeList : JSON.parse(this.nodeList);
      if(data.length > 0 && this.chooseNode == null){
        setTimeout( ()=>{
          let autoNode = Math.min.apply(Math, data.map(function(o) {return o.delay}))
          let autoNodeTitle = data.find(o => o.delay === autoNode);
          this.chooseNode = autoNodeTitle.title
        },1000)
      }
    },
    //获取节点列表
    getNodeList(isRefresh){
      let isExpire = this.$localStore.get("isExpire")
      if(isExpire == null || isExpire == true){
        return false;
      }
      const data = JSON.stringify(this.$localStore.get('nodeList'))
      if( (data != null && data.length > 0) && !isRefresh){
        this.nodeList = data
        // 获取延迟最小的节点
        this.handleMinDelayNode(false)
      }else{
        this.loading = true
        getAllNodeCoreAPI().then(res=>{
          if(res){
            const nodes = res.data.proxies
            this.nodeList = [];
            let availNode = [];
            for(let item in nodes){
              if(nodes[item].type == "Vmess"){//过滤节点
                let history = nodes[item].history;
                let delay = history.length > 0 ? Math.ceil(history[0].delay/10) : 10000;
                availNode.push({
                  title:item,
                  delay:delay == 0 ? 10000 : delay
                })
              }
            }
            this.nodeList = availNode;
            this.$localStore.set('nodeList',null)
            this.$localStore.set('nodeList',JSON.stringify(this.nodeList))
            this.loading = false
            // 获取延迟最小的节点
            this.handleMinDelayNode(true)
          }else{
            this.$message.info("当前无可用节点，请购买会员套餐")
          }
      }).catch(()=>{
        this.$store.commit('CHANGE_ISSART',false)
        this.$localStore.set("isStart",this.isStart)
        this.isStart = false
        this.setProxyHomeConfig(false)
        this.loading = false
      })
      }
      
    },
    //设置、切换节点
    settingNode(nodeName){
      if(!nodeName){
        return false;
      }
      const data = {name: nodeName}
      const mode = this.concatMode == 'Rule' ? '🔰 节点选择' :'GLOBAL';
      changeNodeCoreAPI(mode, data).then(res => {
        if(res){}else{}
      })
    },
    //设置用户根目录文件配置
    setProxyHomeConfig(isStart){
      let that = this
      let text = getProxyConfig(this.isStart)
      const fileName = isStart ? "on.bat": "off.bat";
      let configUrl = writeConfigToPath(text,fileName)
      exec(configUrl,{cwd:'C:/'}, (error, stdout, stderr) => {
        if (error) {
          console.error(`执行的错误: ${JSON.stringify(error)}`)
        }
        //执行后再次改变状态
        that.$electron.ipcRenderer.send("concat-status", that.$localStore.get("isStart"));
      })
    }
  },
  mounted() {
    this.chooseNode = this.$localStore.get("currentNode")
    this.isStart = this.$localStore.get("isStart")
    let isFirst = this.$localStore.get("isFirst");
    if(this.nodeList.length == 0 && !isFirst){
      this.getNodeList(true)
    }
  },
};
</script>

<style>
.concat-page {
  width: 100%;
  height: 100%;
  padding-left: 134px;
  padding-top: 79px;
}
.concat-item {
  width: 100%;
  justify-content: flex-start !important;
}
.concat-input {
  width: 432px;
  height: 46px;
  background: #2b2e38;
  border: 1px solid #4a4e59;
  border-radius: 8px;
  outline: none;
  padding: 10px 40px 10px 20px;
  color: #fff;
}
.concat-div {
  position: relative;
}
.concat-div .down-icon {
  position: absolute;
  top: 15px;
  right: 66px;
  width: 18px;
  height: 18px;
}
.concat-ietm-label {
  color: #ffffff;
}
.concat-radios {
  width: 424px;
  justify-content: space-between !important;
}
.concat-radios img {
  width: 22px;
  height: 22px;
}
.concat-radios .explain {
  width: 18px;
  height: 18px;
}
.explain1:hover+.concat-tip1{
  display: block;
}
.explain2:hover+.concat-tip2{
  display: block;
}
.radio-color {
  color: #b7b7b7;
}
.node-list {
  width: 100%;
  height: 500px;
  overflow-y: auto;
  justify-content: space-between !important;
  flex-wrap: wrap;
  align-items: flex-start;
  padding-right: 2px;
}
.node-item {
  width: 316px;
  height: 80px;
  margin-bottom: 10px;
  justify-content: space-between !important;
}
.node-left-line {
  width: 8px;
  height: 100%;
  background: #2b2e38;
  box-shadow: 0px 2px 7px 0px rgba(22, 23, 23, 0.1);
  border-radius: 4px;
}
.node-item-box {
  width: 300px;
  height: 100%;
  background: #2b2e38;
  border: 1px solid #4a4e59;
  border-radius: 10px;
  padding: 15px 17px;
}
.node-item-title {
  color: #b7b7b7;
  margin-bottom: 10px;
}
.node-item-tip {
  width: 50px;
  height: 26px;
  border-radius: 8px;
  margin-right: 10px;
}
.choose-tip {
  background: #09d0ce;
}
.choose-node-item {
  border: 1px solid #09d0ce;
}
.click-btns {
  width: 222px;
  margin-left: 150px;
}
.click-btns .startorstop {
  width: 222px;
  height: 222px;
}
.start-end-div {
  background: url("../../assets/xm.gif") left top no-repeat;
  background-size: 100% 100%;
}
.dialog-btns {
  height: 56px;
  width: 100%;
  padding: 10px 0;
  color: #b7b7b7;
}
.dialog-btns > div {
  width: 50%;
  height: 100%;
  font-weight: bold;
}
.dialog-cancel {
  border-right: 1px solid #4a4e59;
}
.concat-tip-div{
  position: relative;
}
.concat-tip{
  display: none;
  position: absolute;
  right: -140px;
  top: -62px;
  width: 140px;
  border: 1px solid #303440;
  background: #303440;
  padding: 10px;
  color: #B7B7B7;
  font-size: 12px;
}
</style>